"""
分析命令实现

实现analyze命令的功能。
"""

import click
from typing import Dict, Any, Optional

from .base import BaseCommand
from ...utils.mapping_analyzer import MappingAnalyzer
from ...utils.time_utils import TimeFieldDetector


class AnalyzeCommand(BaseCommand):
    """分析命令实现"""
    
    def __init__(self, config):
        """初始化分析命令"""
        super().__init__(config)
        self.mapping_analyzer = MappingAnalyzer(self.es_client)
        self.time_detector = TimeFieldDetector()
    
    def analyze_index(self, index: str, time_field: Optional[str] = None, sample_size: int = 1000) -> Dict[str, Any]:
        """分析索引
        
        Args:
            index: 索引名称
            time_field: 时间字段
            sample_size: 样本大小
            
        Returns:
            分析结果
        """
        try:
            if not self.validate_index_exists(index):
                raise Exception(f"索引不存在: {index}")
            
            # 获取索引信息
            mapping = self.es_client.get_mapping(index)
            settings = self.es_client.get_settings(index)
            
            # 分析映射
            mapping_analysis = self.mapping_analyzer.analyze_mapping(mapping)
            
            # 检测时间字段
            time_fields = self.time_detector.detect_time_fields(mapping)
            
            # 获取索引统计
            stats = self.es_client.get_index_stats(index)
            index_stats = stats['indices'][index]['total']
            
            return {
                'index': index,
                'mapping_analysis': mapping_analysis,
                'time_fields': time_fields,
                'document_count': index_stats['docs']['count'],
                'store_size': index_stats['store']['size_in_bytes'],
                'settings': settings
            }
            
        except Exception as e:
            self.logger.error(f"分析索引失败: {e}")
            raise
    
    def print_analysis_result(self, result: Dict[str, Any]):
        """打印分析结果"""
        click.echo(f"\n索引分析结果: {result['index']}")
        click.echo("=" * 50)
        
        # 基本信息
        click.echo(f"文档数量: {result['document_count']:,}")
        click.echo(f"存储大小: {self.format_size(result['store_size'])}")
        
        # 映射分析
        mapping_analysis = result.get('mapping_analysis', {})
        if mapping_analysis:
            click.echo(f"\n映射分析:")
            click.echo(f"  字段数量: {mapping_analysis.get('field_count', 0)}")
            click.echo(f"  文本字段: {mapping_analysis.get('text_fields', 0)}")
            click.echo(f"  关键字字段: {mapping_analysis.get('keyword_fields', 0)}")
            click.echo(f"  数值字段: {mapping_analysis.get('numeric_fields', 0)}")
            click.echo(f"  日期字段: {mapping_analysis.get('date_fields', 0)}")
        
        # 时间字段
        time_fields = result.get('time_fields', [])
        if time_fields:
            click.echo(f"\n检测到的时间字段:")
            for field in time_fields:
                click.echo(f"  - {field}")
        else:
            click.echo(f"\n未检测到时间字段")
        
        click.echo()
